package com.ler.yrmall.order.controller;

import com.ler.yrmall.basic.Form;
import com.ler.yrmall.basic.Result;
import com.ler.yrmall.order.entity.OrderEntity;
import com.ler.yrmall.order.form.OrderSubmitForm;
import com.ler.yrmall.order.form.SingleOrderConfirmForm;
import com.ler.yrmall.order.service.OrderService;
import com.ler.yrmall.order.form.OrderFrom;
import com.ler.yrmall.order.vo.OrderConfirmVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;


/**
 * 订单
 * @author Leron
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 列表
     */
    @RequestMapping("/find")
    public Result<?> list(Form request) {
        return Result.ok(orderService.find(request));
    }

    /**
     * 信息
     */
    @RequestMapping("/getById/{id}")
    public Result<?> info(@PathVariable("id") Long id) {
        OrderEntity order = orderService.getById(id);
        return Result.ok(order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public Result<?> save(@RequestBody OrderEntity order) {
        orderService.save(order);
        return Result.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Result<?> update(@RequestBody OrderEntity order) {
        orderService.updateById(order);
        return Result.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public Result<?> delete(@RequestBody Long[] ids) {
        orderService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }

    // ------ 移动端 ----

    @GetMapping("/cartOrderConfirm")
    public Result<?> confirm(@RequestParam(value = "couponId",required = false) Long couponId) {
        OrderConfirmVO orderConfirm = orderService.getCartOrderConfirm(couponId);
        return Result.ok(orderConfirm);
    }

    @PostMapping("/submit")
    public Result<?> submit(@RequestBody OrderSubmitForm request) {
        return Result.ok(orderService.submit(request));
    }

    @GetMapping("/singleOrderConfirm")
    public Result<?> singleOrder(SingleOrderConfirmForm request) {
        OrderConfirmVO orderConfirm = orderService.getSingleOrderConfirm(request);
        return Result.ok(orderConfirm);
    }

    @GetMapping("/memberOrder")
    public Result<?> memberOrder(OrderFrom request) {
        return Result.ok(orderService.memberOrder(request));
    }

    /**
     * 模拟支付回调接口
     * 支付关键步骤
     * 1、每发起一次支付生成一个支付单，关联内部订单号和支付方式，传给三方支付的为支付单号
     * 2、再次发起支付时先将先前所有支付单关闭并主动向支付平台查询最近的一次支付单状态、再生成支付单，防止重复支付
     * 3、支付回调完成之后需要订单变更为已支付状态
     * 4、内部订单超时需要比三方平台支付单单超时时间要长，防止网络通信等原因造成本地订单取消但是用户已支付的情况
     * 5、本地订单取消时向支付平台发起支付查询请求，如果未支付需要发起撤单请求，防止用户停在收银台本地订单超时后仍然能支付
     */
    @GetMapping("/simulatePay")
    public Result<?> simulatePay(Integer payWay,String orderSn) {
        orderService.simulatePay(payWay,orderSn);
        return Result.ok();
    }

}
